package com.hig.onlineexam.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hig.onlineexam.domain.dto.ExamQuestionsListData;
import com.hig.onlineexam.mapper.ExamQuestionsListDataMapper;
import com.hig.onlineexam.service.IExamQuestionsListDataService;

@Service
public class ExamQuestionsListDataServiceImpl implements IExamQuestionsListDataService {
	@Autowired
	ExamQuestionsListDataMapper examQuestionsListDataMapper;
	
	@Override
	public List<ExamQuestionsListData> selectQuestionsList(ExamQuestionsListData examQuestionsListData) {
		// TODO Auto-generated method stub
		String examCode = examQuestionsListData.getExamCode();
		String buildType = examQuestionsListDataMapper.selectManagerBuildType(examCode);
		examQuestionsListData.setBuildType(buildType);
		List<ExamQuestionsListData> list = examQuestionsListDataMapper.selectQuestionsList(examQuestionsListData);
		if ("3".equals(buildType)){
			// 按题型分组
			Map<Integer, List<ExamQuestionsListData>> groupedByType = list.stream()
					.collect(Collectors.groupingBy(ExamQuestionsListData::getQuestionsType));

			List<ExamQuestionsListData> shuffledList = new ArrayList<>();

			// 对每种题型打乱顺序并添加到结果列表中
			for (int type : new int[]{1, 2, 3}) { // 1-判断题, 2-单选, 3-多选
				List<ExamQuestionsListData> questionsOfType = groupedByType.get(type);
				if (questionsOfType != null) {
					Collections.shuffle(questionsOfType); // 打乱该类型的题目
					shuffledList.addAll(questionsOfType);
				}
			}

			// 更新数据库中的题号
			for (int i = 0; i < shuffledList.size(); i++) {
				shuffledList.get(i).setQuestionsNumber(i + 1); // 更新题号为 1, 2, 3...
				examQuestionsListDataMapper.updateNumber(shuffledList.get(i));
			}

			return shuffledList; // 返回打乱后的列表



//// 提取 questionsNumber 列表
//			List<Integer> questionsNumbers = list.stream()
//					.map(ExamQuestionsListData::getQuestionsNumber)
//					.collect(Collectors.toList());
//			List<ExamQuestionsListData> shuffledList = new ArrayList<>();
//// 打乱顺序
//			Collections.shuffle(questionsNumbers);
//
//// 重新设置打乱后的 questionsNumber
//			for (int i = 0; i < list.size(); i++) {
//				list.get(i).setQuestionsNumber(questionsNumbers.get(i));
//				examQuestionsListDataMapper.updateNumber(list.get(i));
//			}
		}
		List<ExamQuestionsListData> data = examQuestionsListDataMapper.selectQuestionsList(examQuestionsListData);
		return data;
	}

}
